<?php

/**
 *类名：360支付回调
 *功能 
 *版本：1.0
 *日期：2016-06-26
'说明：
 */

header("Content-type: text/html; charset=utf-8");
date_default_timezone_set('Asia/Shanghai');
error_log(date('Y-m-d H:i:s',time())."-huidiao \n", 3, 'error.log');
//ini_set('error_reporting', 'E_ALL ^ E_NOTICE');
set_time_limit(0);

include_once("./360sdk/config.php");
include_once("./360sdk/qihoo_msdk/Qihoo/Util.php");
include_once("./360sdk/qihoo_msdk/Qihoo/Pay.php");


include_once("./connConfig.php");
include_once("./mysql.class.php");
include_once("./redis.class.php");
include_once("./httpclient.php");

include_once("./logger.php");


function recv_post_data() {
	$PostData = $_REQUEST;
	return $PostData;

}

function record_post_data($PostData) {
    $date_dir = dirname(__FILE__).'/datalog/'.date('Y-m-d',time());
	if ( !is_dir( $date_dir ) ) {
        mkdir($date_dir, 0700);
    }
    file_put_contents($date_dir. '/' .rand(1000,9999). '-' .time(). '.txt', json_encode($PostData));
}



function connect_db(&$redis, &$mysql, $uid) {
    $ret = $mysql->connect(Config::$mysql_config);
    if (!$ret) {
        echo("mysql connect error.\n");
        exit(0);
    }

    $ret = $redis->initCacheRedis();
    if (!$ret) {
        echo("cache redis connect error.\n");
        exit(0);
    }

    $ret = $redis->initDataRedis($uid);
    if(!$ret) {
        echo("data redis connect error.\n");
        exit(0);
    }
}

function process($respJson,&$payInfArr, &$redis, &$mysql) {
   
    //正确返回
    $cporderid = (string)$respJson['app_order_id'];//应用订单号支付请求时传递，原样返回
    $transid = (string)$respJson['order_id'];//360返回的支付订单号
    $uid = (int)$respJson['app_uid'];//应用分配给用户的id
    $goodsid = (int)$respJson['product_id'];//应用自定义的商品id
    $rmb = (float)$respJson['amount'];//总价,以分为单位
    $result = (int)$respJson['gateway_flag'];//如果支付返回成功，返回success
    //$transtime = (string)$respJson->transtime;

    if ($result != 'success'){
        //echo $result;
       
		error_log(date('Y-m-d H:i:s',time())."-result \n", 3, 'error.log');
        exit(0);
    }

    $row = $mysql->select('applypay','*',array('order_id' =>$cporderid));
	
	
    $goodsid=$row[0]['goods_id'];
    if ( count($row) == 0) {
        //echo("order not exist.\n");
        
		error_log(date('Y-m-d H:i:s',time())."-FAILURE1 \n", 3, 'error.log');
        exit(0);
    }

    $payInfArr = $row[0];
    //var_dump($payInfArr);
    //$uid = (int)$payInfArr['uid'];
    $is_send = (int)$payInfArr['is_send'];

    //var_dump($uid,$is_send);

    if ($is_send == 1) {
      
		error_log(date('Y-m-d H:i:s',time())."-repead order. \n", 3, 'error.log');
        exit(0);
    }


    $data = array(
        'is_send' => 1,
        'type' => 1,
        'iap_transaction_id'=>$transid,
        'update_time' => date('Y-m-d H:i:s',time())
    );
    //$logger->info('applePayTrade', json_encode($data));
    //充值成功后改变状态；

    $mysql->update('applypay',$data,array('order_id' => $cporderid));



    //处理充值，加金币或道具
/*    $goodsid=$goods[0]['id'];
    $logger->info('goodsid', $goods[0]['id']);*/
    $redis->initDataRedis($uid);
    $player = $redis->data_redis->hMGet("hu:{$uid}", array('id','user','exp', 'name', 'money', 'coin','isget_coin_task_reward_record'));
    //var_dump($player);

    if($goodsid==7 && $player['isget_coin_task_reward_record']==1){
        exit("你已经购买过此商品,不可购买");
    }

    //处理充值，加金币或道具

    $goodsadd = $redis->cache_redis->hMGet("hg:{$goodsid}", array("money","rmb","propnum","give_money"));
    error_log("goodadd--".json_encode($goodsadd)."\n\r" ,3,"error_s_log");
    $add_coin = (int)($goodsadd['money']);

    if($goodsid>=20 && $goodsid<30){
        $type=1;
        $proop_info=add_porp($goodsid,$uid ,$redis,(int)$player['money'],(int)$goodsadd['give_money'],$mysql,(int)$goodsadd['rmb']);

    }

    if($goodsid>=30 && $goodsid<50){
        error_log("goodsid--".$goodsid."\n\r" ,3,"error_s_log");
        gift_pay($goodsid,$uid ,$redis,(int)$goodsadd['rmb'],$goodsadd['propnum']);
    }
    if($goodsid>=50){
        error_log("goodsid--".$goodsid."\n\r" ,3,"error_s_log");
        gift_money($goodsadd['give_money'],$mysql,$redis,$uid,$player['money'],(int)$goodsadd['rmb'],$goodsid);
    }

    if($goodsid<10){
        if($goodsid==7){
            $exp=10;
            $redis->data_redis->hSet("hu:{$uid}","isget_coin_task_reward_record",1);


            $happy_num=$redis->data_redis->hGet("hu:{$uid}","301_week_happy_num");//查看当前天数
            if($happy_num==0){
                $redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",6);
                $redis->data_redis->hSet("hu:{$uid}","is_get_week_happy",1);
                $num=$happy_num+6;
                $prop_id=301;
            }else{
                $redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",7);
                $num=$happy_num+7;
                $prop_id=301;
            }

                error_log($num."\n\r" ,3,"error_s_log");

                $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"prop_num":'.$num.',"prop_id":'.$prop_id.'}}';
                $http = new httpclient();
                $http->Get($url);
                error_log($url."\n\r" ,3,"error_s_log");

        }else{
            $exp=(int)$goodsadd['rmb'];
        }

        //给用户加钻石
        $cur_coin = $redis->data_redis->hincrBy("hu:{$uid}","coin",$add_coin);

        //给用户加经验
        $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
        $ret=$redis->data_redis->hMget("hu:{$uid}",array("coin","money","exp"));

        //var_dump($ret);
        //写入变化记录
        if($cur_coin){
            $info =array();
            $info['type'] = '6';
            $info['uid']    = $uid;
            $info['coin']  = $ret['coin'];
            $info['change_coin'] = $add_coin;
            $info['create_time']  = time();
            $mysql->insert("coin_change_rec",$info);//写入金币变化表；
        }else{

            $this->returnData(array(),588,'redis写入失败');
        }

    }


    //插入充值记录
    $pyinfo = array('uid'=>$uid,'rmb'=>$rmb,'goodsid'=>$goodsid,'type'=>10,'create_time'=>time());

    $mysql->insert('payrecord', $pyinfo);

    $num=$proop_info['num'];
    $prop_id=$proop_info['prop_id'];

    
    $http = new httpclient();
    if($goodsid<10){
        $type=2;
        $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"coin":'.$ret['coin'].'}';
    }else{
        $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"prop_num":'.$num.',"prop_id":'.$prop_id.'}}';
    }
    $http->Get($url);
	
    echo 'ok';
    exit;	
}


//充值增加道具
function add_porp($goodsid,$uid,$redis,$money,$give_money,$mysql,$exp){
    switch($goodsid){
        case 21:
            $happy_num=$redis->data_redis->hGet("hu:{$uid}","301_week_happy_num");//查看当前天数
            if($happy_num==0){
                $redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",6);
                $redis->data_redis->hSet("hu:{$uid}","is_get_week_happy",1);
                $num=$happy_num+6;
                $prop_id=301;
            }else{
                $redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",7);
                $num=$happy_num+7;
                $prop_id=301;
            }
            $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
            break;
        case 22:

            $redis->data_redis->hincrBy("hu:{$uid}","money",$give_money);//增加赠送的金币
            $overflow_num=$redis->data_redis->hGet("hu:{$uid}","302_week_overflow_num");//查看当前天数
            if($overflow_num==0){
                $redis->data_redis->hincrBy("hu:{$uid}","302_week_overflow_num",6);//改变天数
                $redis->data_redis->hSet("hu:{$uid}","is_get_week_overflow",1);//改变可领取状态
                $num=$overflow_num+6;
                $prop_id=302;
            }else{
                $redis->data_redis->hincrBy("hu:{$uid}","302_week_overflow_num",7);//改变天数
                $num=$overflow_num+7;
                $prop_id=302;
            }
            $last_money=$money+$give_money;
            insert_moey($uid,$last_money,(int)$give_money,$mysql);//写入金币变化
            $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
            break;
    }
    return array('num'=>$num,'prop_id'=>$prop_id);

}

//处理礼包充值
function gift_pay($goodsid,$uid,$redis,$exp,$num){
    $porp_s=array(
        '101_gift_num'=>31,
        '102_gift_num'=>32,
        '103_gift_num'=>33,
        '104_gift_num'=>34,
        '105_gift_num'=>35,
        '106_gift_num'=>36,
    );
    $keys=array_search($goodsid,$porp_s);
    if($keys){
        $redis->data_redis->hincrBy("hu:{$uid}",$keys,$num);
        $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
    }else{
        returnData(array(),588,'商品不存在');
    }

}

//金币礼包
function gift_money($give_money,$mysql,$redis,$uid,$money,$exp,$goodsid){
    $redis->data_redis->hincrBy("hu:{$uid}","money",$give_money);
    $last_money=$money+$give_money;
    insert_moey($uid,$last_money,(int)$give_money,$mysql);//写入金币变化
    $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
    $porp_s=array(
        '51_gift_bag'=>51,
        '52_gift_bag'=>52,
        '53_gift_bag'=>53,

    );
    $keys=array_search($goodsid,$porp_s);
    if($keys){
        $num=$redis->data_redis->hGet("hu:{$uid}",$keys);
        $unms=$num-1;
        if($num<0){
            $unms=0;
        }
        $redis->data_redis->hSet("hu:{$uid}",$keys,$unms);
    }
}


function insert_moey($uid,$last_money,$give_money,$mysql){
    //var_dump($give_money);
    $info =array();
    $info['type'] = '6';
    $info['uid']    = $uid;
    $info['money']  = $last_money;
    $info['change_money'] = +$give_money;
    $info['create_time']  = time();
    $mysql->insert("money_change_rec",$info);//写入钻石变化表；
}



function insert_pay_record(&$mysql, $payInfArr) {
    //插入充值记录
    $payrecord = array();
    $payrecord['uid'] = (int)$payInfArr['uid'];
    $payrecord['rmb'] = (float)$payInfArr['price'];
    $payrecord['vercode'] = $payInfArr['version'];
    $payrecord['ua'] = $payInfArr['ua'];
    $payrecord['imsi'] = $payInfArr['imsi'];
    $payrecord['imei'] = $payInfArr['imei'];
    $payrecord['cid'] = $payInfArr['cid'];
    $payrecord['order_id'] = $payInfArr['order_id'];
    $payrecord['type'] = 1;
    $payrecord['create_time'] = time();
    $mysql->insert('payrecord', $payrecord);
}

function sys_task_of_pay($uid,&$redis) {
    //首次冲值奖券任务是否完成
    //从奖券任务记录字段中获取奖券任务完成度
    $task_id = 2;//任务号为2
    $task_complete_record_str = $redis->data_redis->hget("hu:{$uid}", "coin_task_complete_record");
    $task_pieces = explode("|", $task_complete_record_str);
    $task_value = $redis->cache_redis->hget("hcointask:{$task_id}", "task_value");
    //如果任务完成度 < 最大任务完成值,则任务完成度加1
    if ((int)$task_pieces[$task_id - 1] < (int)$task_value) {
        $task_pieces[$task_id - 1] += 1;
        //重新组装，任务奖励记录字符串
        $size = count($task_pieces);
        $str = "";
        for ($i = 0; $i < $size; $i++) {
            $str .= $task_pieces[$i];
            if ($i < $size - 1) {
                $str .= "|";
            }
        }
        //重新设置任务奖励记录字符串
        $redis->data_redis->hset("hu:{$uid}", "coin_task_complete_record", $str);
    }
}

function do_trade() {
	
	
	
	$PostData = recv_post_data();
	record_post_data($PostData);
	//
	$qihooPay = new Qihoo_Pay(QIHOO_APP_KEY,QIHOO_APP_SECRET);
    $vailty = $qihooPay->processRequest();
	if(!$vailty){
		
		 error_log(date('Y-m-d H:i:s',time())."-订单验证失败！ \n", 3, 'error.log');
	}
	
    //$PostData = urldecode($PostData);
	$respJson = $PostData ;
	//error_log(json_encode($respJson)."\n\r", 3, 'error.log');
   // error_log(json_encode($PostData)."\n\r", 3, 'error.log');
    //var_dump($PostData);
	
    //var_dump($respJson);
    $redis = new RedisDriver();
    $mysql = new MysqlDriver();
	
    $uid = (int)$respJson['app_uid'];
	error_log('uid:'.$uid."\n\r", 3, 'error.log');
    connect_db($redis, $mysql,$uid);
    process($respJson,$payInfArr,$redis, $mysql);
    //insert_pay_record($mysql,$payInfArr);
    //sys_task_of_pay($uid,$redis);
    $redis->deinitDataRedis();
    $redis->deinitCacheRedis();
    $mysql->close();
    //error_log("SUCCESS----".""."\n\r", 3, 'error.log');
    echo "ok";
    exit();
}

do_trade();

?>
